package com.wxdc.nmgyt.nmgytwydc.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.model.LatLng;
import com.facebook.rebound.SimpleSpringListener;
import com.facebook.rebound.Spring;
import com.facebook.rebound.SpringConfig;
import com.facebook.rebound.SpringSystem;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.wxdc.nmgyt.nmgytwydc.R;
import com.wxdc.nmgyt.nmgytwydc.activity.common.CbYfInfoCommon;
import com.wxdc.nmgyt.nmgytwydc.adapter.YfInfo_RecyclerViewAdapter;
import com.wxdc.nmgyt.nmgytwydc.app.MyApp;
import com.wxdc.nmgyt.nmgytwydc.common.AndroidInterface;
import com.wxdc.nmgyt.nmgytwydc.common.BaiDuMapBasicSetup;
import com.wxdc.nmgyt.nmgytwydc.common.BaiduMapDrawGraph;
import com.wxdc.nmgyt.nmgytwydc.common.CoordinateConvert;
import com.wxdc.nmgyt.nmgytwydc.greendao.GmYfInfoBeanDao;
import com.wxdc.nmgyt.nmgytwydc.greendao.ope.CbYfInfoBeanDaoOpe;
import com.wxdc.nmgyt.nmgytwydc.greendao.ope.CbYfWzInfoBeanDaoOpe;
import com.wxdc.nmgyt.nmgytwydc.greendao.ope.CodeBeanDaoOpe;
import com.wxdc.nmgyt.nmgytwydc.greendao.ope.GmYfInfoBeanDaoOpe;
import com.wxdc.nmgyt.nmgytwydc.greendao.ope.GmYfWzInfoBeanDaoOpe;
import com.wxdc.nmgyt.nmgytwydc.greendao.ope.PdYfInfoBeanDaoOpe;
import com.wxdc.nmgyt.nmgytwydc.greendao.ope.YdInfoBeanDaoOpe;
import com.wxdc.nmgyt.nmgytwydc.model.CbYfInfoBean;
import com.wxdc.nmgyt.nmgytwydc.model.CbYfWzInfoBean;
import com.wxdc.nmgyt.nmgytwydc.model.GmYfInfoBean;
import com.wxdc.nmgyt.nmgytwydc.model.GmYfWzInfoBean;
import com.wxdc.nmgyt.nmgytwydc.model.JcdInfoBean;
import com.wxdc.nmgyt.nmgytwydc.model.JsParamBean;
import com.wxdc.nmgyt.nmgytwydc.model.PdYfInfoBean;
import com.wxdc.nmgyt.nmgytwydc.model.PicUploadStateBean;
import com.wxdc.nmgyt.nmgytwydc.model.YdCodeBean;
import com.wxdc.nmgyt.nmgytwydc.model.YdInfoBean;
import com.wxdc.nmgyt.nmgytwydc.model.YfCodeBean;
import com.wxdc.nmgyt.nmgytwydc.model.backresult.YdAddresultBean;
import com.wxdc.nmgyt.nmgytwydc.model.backresult.YdEditResultBean;
import com.wxdc.nmgyt.nmgytwydc.model.backresult.YfEditResultBean;
import com.wxdc.nmgyt.nmgytwydc.model.backresult.YfRemoveReusltBean;
import com.wxdc.nmgyt.nmgytwydc.service.MyLocationService;
import com.wxdc.nmgyt.nmgytwydc.utils.DeviceTool;
import com.wxdc.nmgyt.nmgytwydc.utils.FileUtil;
import com.wxdc.nmgyt.nmgytwydc.utils.MyLogUtil;
import com.wxdc.nmgyt.nmgytwydc.utils.Network;
import com.wxdc.nmgyt.nmgytwydc.utils.SharedPreferenceUtil;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * Created by Administrator on 2018/3/19.
 * Activity 使用 AgentWeb
 * 1.Activity 继承BaseWebActivity
 * 2.重写getUrl()方法
 */

@SuppressLint("Registered")
public class WebActivity extends BaseWebX5Activity implements SensorEventListener {
    private final String TAG = this.getClass().getSimpleName();
    String url;
    private static final String URL_ADDRESS = "url_address";
    private static final String URLTYPE = "url_type";
    @BindView(R.id.toolbar_title)
    TextView mToolbarTitle;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.webview_bdmap_layout)
    RelativeLayout mWebviewBdmapLayout;
    @BindView(R.id.webcontainer)
    LinearLayout mContainer;
    @BindView(R.id.webview_drawerlayout)
    DrawerLayout mWebviewDrawerlayout;
    @BindView(R.id.left_menu)
    LinearLayout mLeftMenu;
    @BindView(R.id.switch_map_imgbtn)
    ImageView mSwitchMapImgbtn;
    @BindView(R.id.webview_mapview)
    MapView mWebviewMapview;
    @BindView(R.id.baidu_loc_btn)
    ImageButton baiduLocalImgBtn;
    @BindView(R.id.left_menu_yangfang_content)
    LinearLayout mLeftMenuYangfangContent;
    @BindView(R.id.left_menu_ydxxb_btn)
    Button mLeftMenuYdxxbBtn;
    @BindView(R.id.left_menu_cbfzyf_btn)
    Button mLeftMenuCbfzyfBtn;
    @BindView(R.id.left_menu_gmfzyf_btn)
    Button mLeftMenuGmfzyfBtn;
  /*  @BindView(R.id.left_menu_pdyf_btn)
    Button mLeftMenuPdyfBtn;*/
    @BindView(R.id.left_menu_dcb_content)
    LinearLayout mLeftMenuDcbContent;
    @BindView(R.id.yangfang_RecyclerView)
    RecyclerView mYangfangRecyclerView;
    private Context mContext = this;
    private MyApp mApp;
    Spring spring;
    private RxPermissions rxPermissions;
    private BaiDuMapBasicSetup mMapBasicSetup;
    private BaiduMap mBaiduMap;
    private SensorManager mSensorManager;
    private MyLocationService.MyBinder mBinder;
    private Location location;
    private String selectBtnFlag;
    private Unbinder mUnBinder;
    private JcdInfoBean mJcdInfoBean;
    private final int REQUEST_CODE_CHOOSE = 333;//定义请求码常量
    private Gson gson;
    private List<YfCodeBean> yfCodeBeanList;
    private int gmyfQueryFlag ;// 1--->根据样地查询所有样方；2--->新增灌木样方；3--->修改灌木样方
    private int cbyfQueryFlag;//
    @Override
    protected int getLayout() {
        return R.layout.activity_web;
    }

    @Override
    protected void initInject() {
        getActivityComponent().Inject(this);
    }

    @Override
    public String getUrl() {
        url = getIntent().getStringExtra(URL_ADDRESS);
        return url;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mUnBinder = ButterKnife.bind(this);
        gson = new Gson();
        mApp = MyApp.getInstance();
        mToolbar.setTitleTextColor(Color.WHITE);
        mToolbar.setTitle("");
        this.setSupportActionBar(mToolbar);
        if (getSupportActionBar() != null) {
            // Enable the Up button
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog();
            }
        });
        super.initAgentWeb(mContainer, mToolbarTitle, getUrl());

        if (mAgentWebX5 != null) {
            //注入对象
            mAgentWebX5.getJsInterfaceHolder().addJavaObject("android", new AndroidInterface(mAgentWebX5, this, this));
        }

        //设置地图切换动画   TriStateToggleButton 中包含了facebook rebound动画
        spring = SpringSystem.create()
                .createSpring()
                .setSpringConfig(SpringConfig.fromOrigamiTensionAndFriction(86, 3))
                .addListener(new SimpleSpringListener() {
                    @Override
                    public void onSpringUpdate(Spring spring) {
                        float value = (float) spring.getCurrentValue();
                        float scale = 1f - (value * 0.5f);
                        mSwitchMapImgbtn.setScaleX(scale);
                        mSwitchMapImgbtn.setScaleY(scale);
                    }
                });
        mSwitchMapImgbtn.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        spring.setEndValue(1.0f);
                        break;
                    case MotionEvent.ACTION_UP:
                        if (mWebviewBdmapLayout.getVisibility() == View.VISIBLE) {
                            mWebviewBdmapLayout.setVisibility(View.GONE);
                        } else {
                            mWebviewBdmapLayout.setVisibility(View.VISIBLE);
                        }
                    case MotionEvent.ACTION_CANCEL:
                        spring.setEndValue(0.0f);
                        break;
                }

                return true;
            }
        });

        rxPermissions = new RxPermissions(this);
        mSensorManager = (SensorManager) this.getSystemService(SENSOR_SERVICE);//获取传感器管理服务
        mBinder = mApp.getMyBinder();
        /*地图设置*/
        mBaiduMap = mWebviewMapview.getMap();
        mWebviewMapview.removeViewAt(1);//隐藏地图上百度地图logo图标
        mMapBasicSetup = new BaiDuMapBasicSetup(this, mBaiduMap);
        location = mBinder.getLocation();
        mMapBasicSetup.initMap(location, rxPermissions);
        baiduLocalImgBtn.setOnClickListener(mMapBasicSetup.new MyLocListener(location));
        //设置RecyclerView
        mYangfangRecyclerView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        yfCodeBeanList = new ArrayList<>();
        selectBtnFlag = getIntent().getStringExtra(URLTYPE);
        EventBus.getDefault().register(this);//这句话一定不要放在 初始化组件之前
        initJumpPage();
        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                mBaiduMap.hideInfoWindow();
            }

            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                return false;
            }
        });
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                mJcdInfoBean = (JcdInfoBean) marker.getExtraInfo().get("jczInfoObj");
                //生成一个View用户在地图中显示InfoWindow
                ConstraintLayout markerLayout = (ConstraintLayout) LayoutInflater.from(mContext).inflate(R.layout.baidu_infowindow, null);
                ViewHolder viewHolder = null;
                if (markerLayout.getTag() == null) {
                    viewHolder = new ViewHolder();
                    viewHolder.info_window_jcdname_txt = markerLayout.findViewById(R.id.info_window_jcdname_txt);
                    viewHolder.info_window_jcdtype_txt = markerLayout.findViewById(R.id.info_window_jcdtype_txt);
                    viewHolder.info_window_jd_txt = markerLayout.findViewById(R.id.info_window_jd_txt);
                    viewHolder.info_window_wd_txt = markerLayout.findViewById(R.id.info_window_wd_txt);
                    viewHolder.info_window_hb_txt = markerLayout.findViewById(R.id.info_window_hb_txt);
                    viewHolder.info_window_szxzq_txt = markerLayout.findViewById(R.id.info_window_szxzq_txt);
                    markerLayout.setTag(viewHolder);
                }
                viewHolder = (ViewHolder) markerLayout.getTag();
                viewHolder.info_window_jcdname_txt.setText(mJcdInfoBean.getGEMNAME());
                viewHolder.info_window_jcdtype_txt.setText(mJcdInfoBean.getGEMTYPE());
                viewHolder.info_window_jd_txt.setText(String.valueOf(mJcdInfoBean.getJd()));
                viewHolder.info_window_wd_txt.setText(String.valueOf(mJcdInfoBean.getWd()));
                viewHolder.info_window_hb_txt.setText(String.valueOf(mJcdInfoBean.getHB()) + "米");
                viewHolder.info_window_szxzq_txt.setText(String.valueOf(mJcdInfoBean.getXZQMC()));
                //初始化infowindow
                InfoWindow infoWindow = new InfoWindow(markerLayout, marker.getPosition(), -80);
                mBaiduMap.showInfoWindow(infoWindow);
                //移动到当前点
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLng(marker.getPosition()));
                return false;
            }
        });
        BaiduMapDrawGraph.getInstance().drawMarkerToMap(mBaiduMap, mJcdInfoBean);

    }

    /**
     * 复用弹出面板markerLayout的控件
     */
    private class ViewHolder {
        TextView info_window_jcdname_txt;
        TextView info_window_jcdtype_txt;
        TextView info_window_jd_txt;
        TextView info_window_wd_txt;
        TextView info_window_hb_txt;
        TextView info_window_szxzq_txt;
    }

    /*跳转页面*/
    public static void start(Context context, String url, String urlType) {
        Intent intent = new Intent(context, WebActivity.class);
        intent.putExtra(URL_ADDRESS, url);
        intent.putExtra(URLTYPE, urlType);
        context.startActivity(intent);
    }

    @OnClick({R.id.left_menu_ydxxb_btn, R.id.toolbar_title, R.id.left_menu_cbfzyf_btn, R.id.left_menu_gmfzyf_btn, /*R.id.left_menu_pdyf_btn,*/ R.id.addYangfangImgBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.toolbar_title:
                mAgentWebX5.getJsEntraceAccess().quickCallJs("callByAndroidInteraction", "你好Js");
                break;
            case R.id.left_menu_ydxxb_btn://样地信息表
                selectBtnFlag = "ydinfo";
                //super.initAgentWeb(mContainer, mToolbarTitle, mApp.getHTTPYd());
                super.initAgentWeb(mContainer, mToolbarTitle, "file:///android_asset/MobileT_Yd.html");
                initJumpPage();
                break;
            case R.id.left_menu_cbfzyf_btn://草本分种样方
                selectBtnFlag = "cbfzyf";
                super.initAgentWeb(mContainer, mToolbarTitle, "file:///android_asset/MobileT_Cb.html");
                initJumpPage();
                break;
            case R.id.left_menu_gmfzyf_btn://灌木分种样方
                selectBtnFlag = "gmfzyf";
                super.initAgentWeb(mContainer, mToolbarTitle, "file:///android_asset/MobileT_Gm.html");
                initJumpPage();
                break;
            /*case R.id.left_menu_pdyf_btn://频度样方
                selectBtnFlag = "pdyf";
                initJumpPage();
                super.initAgentWeb(mContainer, mToolbarTitle, mApp.getHTTPPd());
                break;*/
            case R.id.addYangfangImgBtn:
                switch (selectBtnFlag) {
                    case "ydinfo":
                        break;
                    case "cbfzyf":
                        YfCodeBean obj = new YfCodeBean();
                        obj.setYfName("*草本样方" + (yfCodeBeanList.size() + 1));
                        obj.setYfCode(String.valueOf(yfCodeBeanList.size() + 1));
                        obj.setYdCode(mJcdInfoBean.getGEMPOINTID());
                        obj.setYdName(mJcdInfoBean.getGEMNAME());
                        yfCodeBeanList.add(obj);
                        break;
                    case "gmfzyf":
                        YfCodeBean gmobj = new YfCodeBean();
                        gmobj.setYfName("*灌木样方" + (yfCodeBeanList.size() + 1));
                        gmobj.setYfCode(String.valueOf(yfCodeBeanList.size() + 1));
                        gmobj.setYdCode(mJcdInfoBean.getGEMPOINTID());
                        gmobj.setYdName(mJcdInfoBean.getGEMNAME());
                        yfCodeBeanList.add(gmobj);
                        break;
                    case "pdyf":
                        //super.initAgentWeb(mContainer, mToolbarTitle, mApp.getHTTPPd());
                        break;
                }
                updateYfListUI();
                break;
        }
        // mWebviewDrawerlayout.closeDrawer(mLeftMenu);
    }

    /*设置按钮选中颜色*/
    private void selectBtnColor(String dcbType) {
        mLeftMenuYdxxbBtn.setTextColor(getResources().getColor(R.color.black));
        mLeftMenuCbfzyfBtn.setTextColor(getResources().getColor(R.color.black));
        mLeftMenuGmfzyfBtn.setTextColor(getResources().getColor(R.color.black));
       // mLeftMenuPdyfBtn.setTextColor(getResources().getColor(R.color.black));
        switch (dcbType) {
            case "ydinfo":
                mLeftMenuYdxxbBtn.setTextColor(getResources().getColor(R.color.white));
                break;
            case "cbfzyf":
                mLeftMenuCbfzyfBtn.setTextColor(getResources().getColor(R.color.white));
                break;
            case "gmfzyf":
                mLeftMenuGmfzyfBtn.setTextColor(getResources().getColor(R.color.white));
                break;
            /*case "pdyf":
                mLeftMenuPdyfBtn.setTextColor(getResources().getColor(R.color.white));
                break;*/
        }

    }

    /*初始化跳转页面*/
    private void initJumpPage() {
        selectBtnColor(selectBtnFlag);
        ViewGroup.LayoutParams params = mLeftMenu.getLayoutParams();
        yfCodeBeanList.clear();
        switch (selectBtnFlag) {
            case "ydinfo":
                mLeftMenuYangfangContent.setVisibility(View.GONE);
                params.width = DeviceTool.getDisplayWindowWidth(this.getWindowManager()).widthPixels * 2 / 5;//设备屏幕宽度的五分之二
                mLeftMenu.setLayoutParams(params);
                break;
            case "cbfzyf":
                mLeftMenuYangfangContent.setVisibility(View.VISIBLE);
                params.width = ViewGroup.LayoutParams.WRAP_CONTENT;
                mLeftMenu.setLayoutParams(params);
                List<CbYfInfoBean> isExistlocal =  CbYfInfoBeanDaoOpe.queryAllForUser(mContext, mJcdInfoBean.getGEMPOINTID()+"-"+Calendar.getInstance().get(Calendar.YEAR));
                int yfNums = isExistlocal.size();
                if (yfNums > 0) {
                    for (int i = 0; i < yfNums; i++) {
                        YfCodeBean loYfcode = new YfCodeBean();
                        loYfcode.setYdName(isExistlocal.get(i).getSAMPLEPLOTNAME());
                        loYfcode.setYdCode(isExistlocal.get(i).getSAMPLEPLOTID());
                        loYfcode.setYfName("*草本样方"+isExistlocal.get(i).getYFH());
                        loYfcode.setYfCode(isExistlocal.get(i).getGRASSID());
                        yfCodeBeanList.add(loYfcode);
                    }
                    curtYfcodeBean = yfCodeBeanList.get(0);
                } else {
                    if(Network.isConnected(mContext) && !SharedPreferenceUtil.getToken().equals("")){//连接网络并且用户是登录状态
                        cbyfQueryFlag = 1;
                        mPersenter.findCbyfInfos(mJcdInfoBean.getGEMPOINTID()+ "-"+Calendar.getInstance().get(Calendar.YEAR));
                    }
                }
                break;
            case "gmfzyf":
                mLeftMenuYangfangContent.setVisibility(View.VISIBLE);
                params.width = ViewGroup.LayoutParams.WRAP_CONTENT;
                mLeftMenu.setLayoutParams(params);
                List<GmYfInfoBean> isExistlocalGm = GmYfInfoBeanDaoOpe.queryAllForUserIdAndYdmc(mContext, mJcdInfoBean.getGEMPOINTID()+"-"+Calendar.getInstance().get(Calendar.YEAR));
                int gmYfNums = isExistlocalGm.size();
                if (gmYfNums > 0) {
                    for (int i = 0; i < gmYfNums; i++) {
                        YfCodeBean loYfcode = new YfCodeBean();
                        loYfcode.setYdName(isExistlocalGm.get(i).getSAMPLEPLOTNAME());
                        loYfcode.setYdCode(isExistlocalGm.get(i).getSAMPLEPLOTID());
                        loYfcode.setYfName("*灌木样方"+isExistlocalGm.get(i).getYFH());
                        loYfcode.setYfCode(isExistlocalGm.get(i).getSHRUBID());
                        yfCodeBeanList.add(loYfcode);
                    }
                } else {
                    if(Network.isConnected(mContext) && !SharedPreferenceUtil.getToken().equals("")){//连接网络并且用户是登录状态
                        gmyfQueryFlag = 1;//根据样地编号-年度，查询所有灌木样方
                        mPersenter.findGmyfInfos(mJcdInfoBean.getGEMPOINTID()+ "-"+Calendar.getInstance().get(Calendar.YEAR));
                    }
                }
                break;
            case "pdyf":
                mLeftMenuYangfangContent.setVisibility(View.GONE);
                params.width = DeviceTool.getDisplayWindowWidth(this.getWindowManager()).widthPixels * 2 / 5;//设备屏幕宽度的五分之二
                mLeftMenu.setLayoutParams(params);
                break;
        }
        updateYfListUI();
    }

    /*关闭或打开侧滑菜单*/
    private void switchDrawerLayout() {
        if (mWebviewDrawerlayout.isDrawerOpen(mLeftMenu)) {
            mWebviewDrawerlayout.closeDrawer(mLeftMenu);
        } else {
            mWebviewDrawerlayout.openDrawer(mLeftMenu);
        }
    }

    /*
    * js调用android方法具体实现
    * */
    private AlertDialog saveDialog,removeDialog,commitDialog,picuploadDialog,removeYfDialog;

    /**
     * 保存数据到本地
     * @param infoStr
     */
    public void showSaveDialog(String infoStr) {
        saveDialog = new AlertDialog.Builder(mContext)
                .setMessage("是否保存数据到本地?")
                .setNegativeButton("否", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (saveDialog != null) {
                            saveDialog.dismiss();
                        }
                    }
                })//
                .setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Log.i(TAG, "onClick: ----------->" + infoStr);
                        switch (selectBtnFlag) {
                            case "ydinfo":
                                saveYdInfoTabFun(infoStr);
                                break;
                            case "cbfzyf":
                                saveCbYfInfoTabFun(infoStr);
                                break;
                            case "gmfzyf":
                                saveGmYfInfoTabFun(infoStr);
                                break;
                            case "pdyf":
                                savePdYfInfoTabFun(infoStr);
                                break;
                        }
                        if (saveDialog != null) {
                            saveDialog.dismiss();
                        }
                    }
                }).create();

        saveDialog.show();
    }
    public void showRemoveDialog(String infoStr,int id) {//删除调查表信息
        removeDialog = new AlertDialog.Builder(mContext)
                .setMessage("是否删除该数据?")
                .setNegativeButton("否", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (removeDialog != null) {
                            removeDialog.dismiss();
                        }
                    }
                })//
                .setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Log.i(TAG, "onClick: ----------->" + infoStr+"-----"+id);
                        switch (selectBtnFlag) {
                            case "ydinfo":
                                break;
                            case "cbfzyf":
                                removeCbYfWzInfoFun(infoStr,id);
                                break;
                            case "gmfzyf":
                                removeGmYfWzInfoFun(infoStr,id);
                                break;
                        }
                        if (removeDialog != null) {
                            removeDialog.dismiss();
                        }
                    }
                }).create();

        removeDialog.show();
    }
    public void showRemoveYfDialog(){
        String _yfName = curtYfcodeBean.getYfName();
        String _yfCode = curtYfcodeBean.getYfCode();
        removeYfDialog = new AlertDialog.Builder(mContext)
                .setMessage("是否删除("+_yfName+")数据?")
                .setNegativeButton("否", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (removeYfDialog != null) {
                            removeYfDialog.dismiss();
                        }
                    }
                })//
                .setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (selectBtnFlag) {
                            case "cbfzyf":
                                CbYfInfoBean _localCbInfo = CbYfInfoBeanDaoOpe.queryEntityForParams(mContext, mJcdInfoBean.getGEMPOINTID() + "-" + Calendar.getInstance().get(Calendar.YEAR), _yfCode);
                                if (_localCbInfo != null) {
                                    CbYfInfoBeanDaoOpe.deleteData(mContext, _localCbInfo);
                                    initJumpPage();
                                } else {
                                    mPersenter.removeCbyfInfo(_yfCode);
                                }
                                break;
                            case "gmfzyf":
                                GmYfInfoBean _localGmInfo = GmYfInfoBeanDaoOpe.queryEntityForParams(mContext, mJcdInfoBean.getGEMPOINTID() + "-" + Calendar.getInstance().get(Calendar.YEAR), _yfCode);
                                if (_localGmInfo != null) {
                                    GmYfInfoBeanDaoOpe.deleteData(mContext, _localGmInfo);
                                    initJumpPage();
                                } else {
                                    mPersenter.removeGmyfInfo(_yfCode);
                                }
                                break;
                        }
                        if (removeYfDialog != null) {
                            removeYfDialog.dismiss();
                        }
                    }
                }).create();
        removeYfDialog.show();
    }
    /**
     * 提交数据到服务器
     * @param dataStr
     */
    private String htmlCommitDataStr;
    public void ShowCommitDialog(String dataStr){
        if (Network.isConnected(mContext)) {
            if ("".equals(SharedPreferenceUtil.getToken())) {
                mApp.showToastLongMessage(mContext,"请登录");
                return;
            }
            commitDialog = new AlertDialog.Builder(mContext)
                    .setMessage("是否提交数据到服务器?")
                    .setNegativeButton("否", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (commitDialog != null) {
                                commitDialog.dismiss();
                            }
                        }
                    })//
                    .setPositiveButton("是", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Log.i(TAG, "onClick: -----commit------>" + dataStr);
                            switch (selectBtnFlag) {
                                case "ydinfo":
                                    htmlCommitDataStr = dataStr;
                                    YdInfoBean ydInfoBean = gson.fromJson(htmlCommitDataStr, YdInfoBean.class);
                                    String cjYear = ydInfoBean.getCJDATA() == null ? "" : ydInfoBean.getCJDATA().split("-")[0];
                                    mPersenter.findYdInfo(mJcdInfoBean.getGEMPOINTID()+"-"+cjYear);
                                    break;
                                case "cbfzyf":
                                    htmlCommitDataStr = dataStr;
                                    CbYfInfoBean cbYfInfoBean = gson.fromJson(dataStr, CbYfInfoBean.class);
                                    if (cbYfInfoBean.getGRASSID().split("-").length == 1) {
                                        cbyfQueryFlag = 2;
                                        mPersenter.findCbyfInfos(mJcdInfoBean.getGEMPOINTID() + "-" + Calendar.getInstance().get(Calendar.YEAR));
                                    } else {
                                        cbyfQueryFlag = 3;
                                        mPersenter.findCbyfInfos(cbYfInfoBean.getGRASSID());
                                    }
                                    break;
                                case "gmfzyf":
                                    htmlCommitDataStr = dataStr;
                                    GmYfInfoBean gmYfInfoBean = gson.fromJson(dataStr, GmYfInfoBean.class);
                                    if (gmYfInfoBean.getSHRUBID().split("-").length == 1) {//属于新增的样方，通过样地编号-年度，查询出所有样方数量，并将该样方增加
                                        gmyfQueryFlag = 2;//新增灌木样方
                                        mPersenter.findGmyfInfos(mJcdInfoBean.getGEMPOINTID() + "-" + Calendar.getInstance().get(Calendar.YEAR));
                                    } else {
                                        gmyfQueryFlag = 3;//修改灌木样方
                                        mPersenter.findGmyfInfos(gmYfInfoBean.getSHRUBID());
                                    }

                                    break;
                                case "pdyf":
                                    savePdYfInfoTabFun(dataStr);
                                    break;
                            }
                            if (commitDialog != null) {
                                commitDialog.dismiss();
                            }
                        }
                    }).create();

            commitDialog.show();
        } else {
            mApp.showToastLongMessage(mContext,"无法连接网络");
        }
    }
    //打开相机或相册
    public void openAlbumAndCamera(int selectPicNum) {
        Matisse.from(WebActivity.this)
                .choose(MimeType.ofAll(), false)//图片类型
                .countable(true)//true:选中后显示数字;false:选中后显示对号
                .capture(true)//选择照片时，是否显示拍照
                .captureStrategy(new CaptureStrategy(true, "com.wxdc.nmgyt.nmgytwydc.fileprovider"))//参数1 true表示拍照存储在共有目录，false表示存储在私有目录；参数2与 AndroidManifest中authorities值相同，用于适配7.0系统 必须设置
                .maxSelectable(selectPicNum)//可选的最大数
                .theme(R.style.Matisse_Zhihu)//主题  暗色主题 R.style.Matisse_Dracula
                .originalEnable(true)
                .maxOriginalSize(10)
                .imageEngine(new GlideEngine())//图片加载引擎
                .forResult(REQUEST_CODE_CHOOSE);//请求码
    }

    /*
    *   页面返回结果
    * */
    private List<String> ydPicUrls;
    private List<String> selectUrls;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        selectUrls = null;
        mAgentWebX5.getJsEntraceAccess().quickCallJs("callJsGetCjDate");//获取当前采集时间-----作为图片命名元素之一
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            Log.i(TAG, "onActivityResult: -----------相册选中返回结果:-----------" + Matisse.obtainResult(data) + "-----path------" + Matisse.obtainPathResult(data));
            selectUrls = Matisse.obtainPathResult(data);
            //如果拍照更新到图库
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri = Uri.parse("file://" + Matisse.obtainPathResult(data).get(0));
            intent.setData(uri);
            Log.i(TAG, "onActivityResult: -------uri---" + uri);
            mContext.sendBroadcast(intent);
        }
        Log.i(TAG, "onActivityResult: -------------" + resultCode);
    }

        /*
        * 地图
        *
        * */
    @Override
    public void onSensorChanged(SensorEvent event) {
        mMapBasicSetup.setSensor(event);
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (mWebviewDrawerlayout.isDrawerOpen(mLeftMenu)) {
            mWebviewDrawerlayout.closeDrawer(mLeftMenu);
        } else {
            super.showDialog();
        }
        return true;
    }

    /*
    * EventBus*/
    private String getJcdInfoJson;

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void jcdInfoEvent(JcdInfoBean infoBean) {
        mJcdInfoBean = infoBean;
        getJcdInfoJson = gson.toJson(infoBean);
    }
    /*
    * webview初始化页面完成
    * */
    public void webViewInitComplete() {
        if (mJcdInfoBean != null) {
            YdInfoBean bean = YdInfoBeanDaoOpe.queryEntityForParams(mContext,mJcdInfoBean.getGEMPOINTID());//查询本地是否已填写样地调查表数据
            switch (selectBtnFlag) {
                case "ydinfo":
                    mAgentWebX5.getJsEntraceAccess().quickCallJs("callJsInitJcdInfo", getJcdInfoJson, SharedPreferenceUtil.getUserrealname());//页面加载基本监测点信息数据
                    if (bean != null) {
                        mAgentWebX5.getJsEntraceAccess().quickCallJs("callJsInitYdInfo", gson.toJson(bean));//属性信息
                        if (bean.getIMGPATH() != null && !bean.getIMGPATH().equals("")) {
                            String[] s = bean.getIMGPATH().split(",");
                            Log.i(TAG, "webViewInitComplete: --------" + s.length);
                            int selectYdpicNum = s.length;
                            for (int i = 0; i < selectYdpicNum; i++) {
                                s[i] = s[i] + "?" + Math.random();
                                Log.i(TAG, "webViewInitComplete: --------" + s[i]);
                            }
                           mAgentWebX5.getJsEntraceAccess().quickCallJs("callJsShowPic", gson.toJson(s));
                        }
                    }
                    break;
                case "cbfzyf":
                    //页面初始化完成加载样地基本信息、 样方编号、利用方式、利用强度、记录人等样地信息表中内容
                    CbYfInfoBean cbYfInfoBean = CbYfInfoBeanDaoOpe.queryEntityForParams(mContext, mJcdInfoBean.getGEMPOINTID()+"-"+Calendar.getInstance().get(Calendar.YEAR),curtYfcodeBean.getYfCode());
                    if (cbYfInfoBean != null) {//加载本地数据
                        mAgentWebX5.getJsEntraceAccess().quickCallJs("callJsLocalExistCbYfInfo", gson.toJson(cbYfInfoBean));
                        if (cbYfInfoBean.getIMGPATH() != null) {
                            /*String[] s = cbYfInfoBean.getIMGPATH().split(",");
                            Log.i("TAG", "cbfzyf------webViewInitComplete: --------" + s.length);
                            for (int i = 0; i < s.length; i++) {
                                s[i] = s[i] + "?" + Math.random();
                                Log.i("TAG", "cbfzyf-------webViewInitComplete: --------" + s[i]);
                            }*/
                            String imgpath = cbYfInfoBean.getIMGPATH();
                            imgpath = imgpath+"?"+Math.random();
                            mAgentWebX5.getJsEntraceAccess().quickCallJs("callJsShowPic", gson.toJson(imgpath));
                        }
                    } else {//加载服务器数据()
                        mAgentWebX5.getJsEntraceAccess().quickCallJs("callJsInitCbYfInfo", gson.toJson(curtYfcodeBean));//属性信息
                    }
                    break;
                case "gmfzyf":
                    GmYfInfoBean gmYfInfoBean =  GmYfInfoBeanDaoOpe.queryEntityForParams(mContext,mJcdInfoBean.getGEMPOINTID()+"-"+Calendar.getInstance().get(Calendar.YEAR), curtYfcodeBean.getYfCode());
                    if (gmYfInfoBean != null) {
                        mAgentWebX5.getJsEntraceAccess().quickCallJs("callJsLocalExistGmYfInfo", gson.toJson(gmYfInfoBean));
                    } else {
                        mAgentWebX5.getJsEntraceAccess().quickCallJs("callJsInitGmYfInfo", gson.toJson(curtYfcodeBean));
                    }
                    break;
                case "pdyf":
                    if (bean != null) {
                        mAgentWebX5.getJsEntraceAccess().quickCallJs("callJsInitPdYfInfo", gson.toJson(bean));//属性信息
                        PdYfInfoBean pdYfInfoBean = null;// PdYfInfoBeanDaoOpe.queryAllForUserIdAndYdmc(mContext, bean.getUserid(), bean.getSAMPLEPLOTNAME());
                        if (pdYfInfoBean != null) {
                            mAgentWebX5.getJsEntraceAccess().quickCallJs("callJsLocalExistPdYfInfo", gson.toJson(pdYfInfoBean));
                        }
                    } else {
                        mApp.showToastLongMessage(mContext, "请先进行样地信息调查表的填写");
                        mAgentWebX5.getJsEntraceAccess().quickCallJs("callJsError");
                    }
                    break;
            }
        }
    }

    /*
    *  获取填表信息(获取采集日期并将图片显示在网页上)
    * */
    public void getHtmlPageDateInfo(String str, boolean isYszPic) {
        JsParamBean jsParamBean = gson.fromJson(str, JsParamBean.class);
        String dateStr = jsParamBean.getDATE();
        String yszName = jsParamBean.getNAME();
        String xzdm = "";
        if (ydPicUrls == null) {
            ydPicUrls = new ArrayList<>();
        }
        if (mJcdInfoBean != null) {
            xzdm = mJcdInfoBean.getZZDM().substring(2);
        }
        //获取图片信息并按命名要求对图片重命名
        switch (selectBtnFlag) {
            case "ydinfo":
                int len = 0;
                if (selectUrls != null) {
                    len = selectUrls.size();
                }
                ydPicUrls.clear();
                for (int i = 0; i < len; i++) {
                    // picName: 例如：锡盟-黄花沟-景观-东（西、南、北）152502HHG20160708JG01E（W、S、N）
                    if (i == 0) {
                        ydPicUrls.add(FileUtil.copyImage(selectUrls.get(i), xzdm + mJcdInfoBean.getGEMNAMESX() + dateStr.replace("-", "") + "JG01E"));
                    } else if (i == 1) {
                        ydPicUrls.add(FileUtil.copyImage(selectUrls.get(i), xzdm + mJcdInfoBean.getGEMNAMESX() + dateStr.replace("-", "") + "JG02W"));
                    } else if (i == 2) {
                        ydPicUrls.add(FileUtil.copyImage(selectUrls.get(i), xzdm + mJcdInfoBean.getGEMNAMESX() + dateStr.replace("-", "") + "JG03S"));
                    } else if (i == 3) {
                        ydPicUrls.add(FileUtil.copyImage(selectUrls.get(i), xzdm + mJcdInfoBean.getGEMNAMESX() + dateStr.replace("-", "") + "JG04N"));
                    }
                }
                mAgentWebX5.getJsEntraceAccess().quickCallJs("callJsShowPic", gson.toJson(ydPicUrls));
                break;
            case "cbfzyf":
                ydPicUrls.clear();
                if (selectUrls != null) {
                    //例如：锡盟-黄花沟—样方1    152502HHG20160708YF101
                    String _yf = curtYfcodeBean.getYfCode();
                    if(_yf.split("-").length != 1){
                        _yf = _yf.substring(_yf.lastIndexOf("-")+ 1);
                    }
                    String yfImgUrl = FileUtil.copyImage(selectUrls.get(0), xzdm + mJcdInfoBean.getGEMNAMESX() + dateStr.replace("-", "") + "YF" +_yf + "01");
                    mAgentWebX5.getJsEntraceAccess().quickCallJs("callJsShowPic", yfImgUrl);
                }
                break;
        }

    }

    /**
     * 获得当前优势种照片
     *
     * @param wzmc
     */
    public void getCurtYszPic(String wzmc) {
        CbYfInfoBean mYfInfoBean = null;
        CbYfWzInfoBean mWzInfoBean = null;
        if (mJcdInfoBean != null) {
            //mYfInfoBean = CbYfInfoBeanDaoOpe.queryEntityForParams(mContext, "1", mJcdInfoBean.getGEMNAME(), curtYfcodeBean);
        }
        if (mYfInfoBean != null) {
            mWzInfoBean =CbYfWzInfoBeanDaoOpe.queryEntityByParams(mContext, mYfInfoBean.getId(), wzmc);
        }
        if (mWzInfoBean != null) {
            //mAgentWebX5.getJsEntraceAccess().quickCallJs("callJsShowYszPic", mWzInfoBean.getYSZPICURL()+ "?" + Math.random());
        }

    }

    /*
    * 保存样地信息到本地数据库
    * */
    private void saveYdInfoTabFun(String ydInfoStr) {
        YdInfoBean bean = gson.fromJson(ydInfoStr, YdInfoBean.class);
        Log.i(TAG, "saveYdInfoTabFun: --------传入数据------->" + bean.toString());
        YdInfoBean curtDbExistBean = YdInfoBeanDaoOpe.queryEntityForParams(mContext, bean.getSAMPLEPLOTID());//判断当前数据库是否有该数据
        if (curtDbExistBean != null) {
            bean.setId(curtDbExistBean.getId());
            YdInfoBeanDaoOpe.updateData(mContext, bean);
            Log.i(TAG, "saveYdInfoTabFun: -------------->更新数据");
            MyApp.getInstance().showToastLongMessage(mContext, "数据修改成功!");
        } else {
            YdInfoBeanDaoOpe.saveData(mContext, bean);
            Log.i(TAG, "saveYdInfoTabFun: --------------->保存数据");
            MyApp.getInstance().showToastLongMessage(mContext, "数据保存成功！");
        }
    }


    /*
    * 保存草本样方数据到本地数据库
    * */
    private void saveCbYfInfoTabFun(String cbYfInfoStr) {
        Log.i(TAG, "saveCbYfInfoTabFun: ---------->"+cbYfInfoStr);
        CbYfInfoBean bean = gson.fromJson(cbYfInfoStr, CbYfInfoBean.class);
        if (bean.getGRASSID().split("-").length == 1) {
            bean.setYFH(bean.getGRASSID());
        } else {
            bean.setYFH(bean.getGRASSID().substring(bean.getGRASSID().lastIndexOf("-")+1));
        }
        //Log.i(TAG, "saveCbYfInfoTabFun: ---------->"+bean.getYFH());
        CbYfInfoBean curtDbExistYfData = CbYfInfoBeanDaoOpe.queryEntityForParams(mContext, bean.getSAMPLEPLOTID(), bean.getGRASSID());
        if (curtDbExistYfData != null) {
            bean.setId(curtDbExistYfData.getId());
            CbYfInfoBeanDaoOpe.updateData(mContext, bean);
            MyApp.getInstance().showToastLongMessage(mContext, "数据修改成功!");
        } else {
            CbYfInfoBeanDaoOpe.saveData(mContext, bean);
            MyApp.getInstance().showToastLongMessage(mContext, "数据保存成功！");
        }
    }

    /*
   * 保存灌木样方数据到本地数据库
   * */
    private void saveGmYfInfoTabFun(String gmYfInfoStr) {
        GmYfInfoBean bean = gson.fromJson(gmYfInfoStr, GmYfInfoBean.class);
        //bean.setSAMPLEPLOTID(mJcdInfoBean.getGEMPOINTID()+"-"+Calendar.getInstance().get(Calendar.YEAR));
        if (bean.getSHRUBID().split("-").length == 1) {
            bean.setYFH(bean.getSHRUBID());
        } else {
            bean.setYFH(bean.getSHRUBID().substring(bean.getSHRUBID().lastIndexOf("-")+1));
        }
        GmYfInfoBean currDbExiseGmYfData = GmYfInfoBeanDaoOpe.queryEntityForParams(mContext, bean.getSAMPLEPLOTID(),bean.getSHRUBID());
        if (currDbExiseGmYfData != null) {
            bean.setId(currDbExiseGmYfData.getId());
            GmYfInfoBeanDaoOpe.updateData(mContext, bean);
            MyApp.getInstance().showToastLongMessage(mContext, "数据修改成功!");
        } else {
            GmYfInfoBeanDaoOpe.saveData(mContext, bean);
            MyApp.getInstance().showToastLongMessage(mContext, "数据保存成功!");
        }
        Log.i(TAG, "saveGmYfInfoTabFun: -------------------->" + currDbExiseGmYfData);
    }

    /**
     * 保存频度样方数据到本地数据库
     * @param pdYfInfoStr
     */
    private void savePdYfInfoTabFun(String pdYfInfoStr){
        Log.i(TAG, "savePdYfInfoTabFun: --------------->"+pdYfInfoStr);
        PdYfInfoBean bean = gson.fromJson(pdYfInfoStr, PdYfInfoBean.class);
        /*bean.setUserid("1");
        PdYfInfoBean currDbExistPdYfData = PdYfInfoBeanDaoOpe.queryAllForUserIdAndYdmc(mContext, bean.getUserid(), bean.getSAMPLEPLOTNAME());
        if (currDbExistPdYfData != null) {
            bean.setId(currDbExistPdYfData.getId());
            PdYfInfoBeanDaoOpe.updateData(mContext,bean);
            MyApp.getInstance().showToastLongMessage(mContext, "数据修改成功!");
        } else {
            PdYfInfoBeanDaoOpe.saveData(mContext, bean);
            MyApp.getInstance().showToastLongMessage(mContext, "数据保存成功!");
        }*/
    }
    /**
     * 删除草本样方物种信息
     * @param cbYfWzInfoStr
     */
    private void removeCbYfWzInfoFun(String cbYfWzInfoStr,int id){
        Log.i(TAG, "removeCbYfWzInfoFun: ------------->"+cbYfWzInfoStr);
        CbYfWzInfoBean wzInfoBean = gson.fromJson(cbYfWzInfoStr, CbYfWzInfoBean.class);
        CbYfInfoBean cbYfInfoBean = CbYfInfoBeanDaoOpe.queryEntityForParams(mContext, mJcdInfoBean.getGEMPOINTID()+"-"+Calendar.getInstance().get(Calendar.YEAR), curtYfcodeBean.getYfCode());
        if (cbYfInfoBean != null) {
            int len =  (cbYfInfoBean.getGRASS_WZ() == null ? 0 : cbYfInfoBean.getGRASS_WZ().size());
            for (int i = 0; i < len; i++) {
                if (cbYfInfoBean.getGRASS_WZ().get(i).getWZMC().equals(wzInfoBean.getWZMC())) {
                    CbYfWzInfoBeanDaoOpe.updateData(mContext, cbYfInfoBean.getGRASS_WZ().get(i));
                    mAgentWebX5.getJsEntraceAccess().quickCallJs("callJsRemoveWzInfo",gson.toJson(wzInfoBean), String.valueOf(id));
                }
            }
        } else {
            mAgentWebX5.getJsEntraceAccess().quickCallJs("callJsRemoveWzInfo",gson.toJson(wzInfoBean),String.valueOf(id));
        }
    }

    /**删除灌木样方物种信息
     * @param gmYfWzInfoStr
     * @param id
     */
    private void removeGmYfWzInfoFun(String gmYfWzInfoStr,int id){
        Log.i(TAG, "removeGmYfWzInfoFun: ------------"+gmYfWzInfoStr);
        GmYfWzInfoBean gmYfWzInfoBean = gson.fromJson(gmYfWzInfoStr, GmYfWzInfoBean.class);
        GmYfInfoBean gmYfInfoBean = GmYfInfoBeanDaoOpe.queryEntityForParams(mContext, mJcdInfoBean.getGEMPOINTID()+"-"+Calendar.getInstance().get(Calendar.YEAR), curtYfcodeBean.getYfCode());
        if (gmYfInfoBean != null) {
            int len = (gmYfInfoBean.getSHRUB_WZ() == null ? 0 : gmYfInfoBean.getSHRUB_WZ().size());
            for (int i = 0; i < len; i++) {
                if (gmYfInfoBean.getSHRUB_WZ().get(i).getWZMC().equals(gmYfWzInfoBean.getWZMC())) {
                    GmYfWzInfoBeanDaoOpe.updateData(mContext, gmYfInfoBean.getSHRUB_WZ().get(i));
                    mAgentWebX5.getJsEntraceAccess().quickCallJs("callJsRemoveWzInfo", gson.toJson(gmYfWzInfoBean), String.valueOf(id));
                }
            }
        } else {
            mAgentWebX5.getJsEntraceAccess().quickCallJs("callJsRemoveWzInfo", gson.toJson(gmYfWzInfoBean), String.valueOf(id));
        }
    }
    /*
    * 更新样方列表信息
    * */
    private YfInfo_RecyclerViewAdapter mYfInfoRecyclerViewAdapter;
    private YfCodeBean curtYfcodeBean;//当前样方编号

    private void updateYfListUI() {
        if (mYfInfoRecyclerViewAdapter == null) {
            mYfInfoRecyclerViewAdapter = new YfInfo_RecyclerViewAdapter(mContext, yfCodeBeanList);
            mYangfangRecyclerView.setAdapter(mYfInfoRecyclerViewAdapter);
            mYangfangRecyclerView.addItemDecoration(new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL));//添加默认分割线
            mYfInfoRecyclerViewAdapter.setItemClickListener(new YfInfo_RecyclerViewAdapter.RecycleViewOnItemClickListener() {
                @Override
                public void onItemClick(int position) {
                    curtYfcodeBean = yfCodeBeanList.get(position);
                    mAgentWebX5.getJsEntraceAccess().quickCallJs("callJsWebViewInitComplete");
                }
            });
            mYfInfoRecyclerViewAdapter.setItemLongClickListener(new YfInfo_RecyclerViewAdapter.RecycleViewOnItemLongClickListener() {
                @Override
                public void onItemLongClick(int position) {
                    curtYfcodeBean = yfCodeBeanList.get(position);
                    showRemoveYfDialog();
                }
            });
        } else {
            mYfInfoRecyclerViewAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 跳转到新增物种界面
     */
    public void jumpAddWzActivity(String dataInfo){
        //1.保存当前所填信息-----------------想多了，不用这样的
        Log.i(TAG, "jumpAddWzActivity: ------------>"+dataInfo);
        //2.跳转界面
        AddWzActivity.start(mContext);
    }
    //-----------------------------
    private List<String> picUrls;
    public void uploadpic(String infoStr){
        if(infoStr.equals("error")){
            mApp.showToastLongMessage(mContext,"请选择新图片在操作");
            return;
        }
        picuploadDialog = new AlertDialog.Builder(mContext)
                .setMessage("是否上传照片?")
                .setNegativeButton("否", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (picuploadDialog != null) {
                            picuploadDialog.dismiss();
                        }
                    }
                })//
                .setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (selectBtnFlag) {
                            case "ydinfo":
                                multiUploadPicFun(infoStr);
                                break;
                            case "cbfzyf":
                                singleUploadPicFun(infoStr);
                                break;
                        }
                        if (picuploadDialog != null) {
                            picuploadDialog.dismiss();
                        }
                    }
                }).create();

        picuploadDialog.show();
    }
    private void multiUploadPicFun(String urlInfo){
        if (Network.isConnected(mContext)) {
            if ("".equals(SharedPreferenceUtil.getToken())) {
                mApp.showToastLongMessage(mContext, "请登录");
                return;
            }
            String[] urls = urlInfo.split(",");
            picUrls = Arrays.asList(urls);
            mCircleProgressDialog.setText("图片上传中...");
            mCircleProgressDialog.showDialog();
            mPersenter.multiUploadPics(picUrls);//上传图片
        } else {
            mApp.showToastLongMessage(mContext,"无法连接网络");
        }
    }
    private void singleUploadPicFun(String urlInfo){
        if (Network.isConnected(mContext)) {
            if ("".equals(SharedPreferenceUtil.getToken())) {
                mApp.showToastLongMessage(mContext, "请登录");
                return;
            }
            mCircleProgressDialog.setText("图片上传中...");
            mCircleProgressDialog.showDialog();
            mPersenter.singleUploadPic(urlInfo);//上传图片
        } else {
            mApp.showToastLongMessage(mContext,"无法连接网络");
        }
    }
    @Override
    public void showError(String msg) {
        mApp.showToastLongMessage(mContext,msg);
        if(mCircleProgressDialog != null && mCircleProgressDialog.isShowing()){
            mCircleProgressDialog.dismiss();
        }
    }

    @Override
    public void singlePicUploadResult(PicUploadStateBean result) {
        _picname = "";
        if (result != null ) {
            if ("1".equals(result.getState())) {//图片上传成功，更新物种信息
                _picname = result.getName();
                mApp.showToastLongMessage(mContext, "success");
            } else {
                mApp.showToastLongMessage(mContext, "fail");
            }
        }
        mCircleProgressDialog.dismiss();
    }
    private String _picname = "";
    @Override
    public void multiPicUploadResult(List<PicUploadStateBean> result) {
        _picname = "";
        if (result != null && result.size() > 0) {
            for (PicUploadStateBean obj : result) {
                if ("1".equals(obj.getState())) {
                    _picname += obj.getName() + ",";
                } else {
                    mApp.showToastLongMessage(mContext,obj.getName()+"上传失败");
                }
            }
            _picname = _picname.substring(0, _picname.lastIndexOf(","));
            mApp.showToastLongMessage(mContext,"success");
        }
        mCircleProgressDialog.dismiss();
    }

    /**
     * 服务器是否有样地信息
     * @param responseBody
     */
    @Override
    public void isYdInfoExist(ResponseBody responseBody) {
        try {
            String jsonStr = new String(responseBody.bytes());
            YdInfoBean curtDataObj =  gson.fromJson(htmlCommitDataStr, YdInfoBean.class);//将页面提交的数据转换成Java对象
            if (jsonStr .equals("null")) {//新增样地
                 curtDataObj.setPICNAME(_picname);
                 mPersenter.addYdInfo(curtDataObj);
            } else {//修改样地
                YdInfoBean obj = gson.fromJson(jsonStr, YdInfoBean.class);
                curtDataObj.setSAMPLEPLOTID(obj.getSAMPLEPLOTID());
                curtDataObj.setVERSION(obj.getVERSION());
                if (!"".equals(_picname)) {
                    curtDataObj.setPICNAME(_picname);
                }
                mPersenter.editYdInfo(curtDataObj);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    /**
     * 新增样地信息返回结果
     * @param result
     */
    @Override
    public void addYdInfoResult(YdAddresultBean result) {
        mApp.showToastLongMessage(mContext,result.getReMessage());
        if ("Success".equals(result.getReMessage())) {//删除本地保存数据
            YdInfoBean localExistObj = YdInfoBeanDaoOpe.queryEntityForParams(mContext, mJcdInfoBean.getGEMPOINTID());
            if (localExistObj != null) {
                YdInfoBeanDaoOpe.deleteData(mContext,localExistObj);
            }
        }
    }

    /**
     * 修改样地返回结果
     * @param resultBean
     */
    @Override
    public void editYdInfoResult(YdAddresultBean resultBean) {
        mApp.showToastLongMessage(mContext,resultBean.getReMessage());
        if ("Success".equals(resultBean.getReMessage())) { //删除本地保存数据
            YdInfoBean localExistObj = YdInfoBeanDaoOpe.queryEntityForParams(mContext, mJcdInfoBean.getGEMPOINTID());
            if (localExistObj != null) {
                YdInfoBeanDaoOpe.deleteData(mContext,localExistObj);
            }
        }
    }
    //-----------------------------草本-----------------------------------------------------------
    /**
     * 如果要查询一个样地下的所有样方返回结果
     * @param cbYfInfoBeanList
     */
    @Override
    public void findCbyfInfoResults(List<CbYfInfoBean> cbYfInfoBeanList) {
        int cbYfNums = cbYfInfoBeanList.size();
        Log.i(TAG, "findCbyfInfoResult: ------------>"+cbYfNums);
        if(cbyfQueryFlag == 1){
            yfCodeBeanList.clear();
            if (cbYfNums > 0) {
                for (int i = 0; i < cbYfNums; i++) {
                    YfCodeBean bean = new YfCodeBean();
                    bean.setYfCode(cbYfInfoBeanList.get(i).getGRASSID());
                    bean.setYfName("草本样方" + (i + 1));
                    yfCodeBeanList.add(bean);
                }
                curtYfcodeBean = yfCodeBeanList.get(0);
               //mAgentWebX5.getJsEntraceAccess().quickCallJs("callJsWebViewInitComplete");
            }
            updateYfListUI();
        }else if(cbyfQueryFlag == 2){//新增
            CbYfInfoBean cbYfInfoBean = gson.fromJson(htmlCommitDataStr, CbYfInfoBean.class);//页面提交数据
            cbYfInfoBean.setGRASSID(String.valueOf(cbYfNums+1));
            cbYfInfoBean.setPICNAME(_picname);
            mPersenter.addCbyfInfo(cbYfInfoBean);
        } else if (cbyfQueryFlag == 3) {
            CbYfInfoBean cbYflocBean = gson.fromJson(htmlCommitDataStr, CbYfInfoBean.class);//页面提交数据
            CbYfInfoBean serYfInfoBean = cbYfInfoBeanList.get(0);
            cbYflocBean.setVERSION(serYfInfoBean.getVERSION());
            if(!"".equals(_picname)){
                cbYflocBean.setPICNAME(_picname);
            }
            int locWzLen = cbYflocBean.getGRASS_WZ().size();
            int serWzLen = serYfInfoBean.getGRASS_WZ().size();
            for (int i = 0; i < locWzLen;i++) {
                for (int j = 0; j < serWzLen;j++) {
                    if (cbYflocBean.getGRASS_WZ().get(i).getWZDM().equals(serYfInfoBean.getGRASS_WZ().get(j).getWZDM())) {
                        cbYflocBean.getGRASS_WZ().get(i).setID(serYfInfoBean.getGRASS_WZ().get(j).getID());
                        cbYflocBean.getGRASS_WZ().get(i).setGRASSID(serYfInfoBean.getGRASS_WZ().get(i).getGRASSID());
                        cbYflocBean.getGRASS_WZ().get(i).setVERSION(serYfInfoBean.getGRASS_WZ().get(j).getVERSION());
                    }
                }
            }
            mPersenter.editCbyfInfo(cbYflocBean);
        }
        cbyfQueryFlag = 0;
    }
    @Override
    public void addCbyfInfoResult(YfEditResultBean result) {
        if ("200".equals(result.getCode()) && result.getUs().equals("0")) {//删除本地保存数据
            mApp.showToastLongMessage(mContext,result.getReMessage());
            CbYfInfoBean localExistObj = CbYfInfoBeanDaoOpe.queryEntityForParams(mContext,mJcdInfoBean.getGEMPOINTID()+"-"+Calendar.getInstance().get(Calendar.YEAR), curtYfcodeBean.getYfCode());
            if (localExistObj != null) {
                CbYfInfoBeanDaoOpe.deleteData(mContext,localExistObj);
            }
            initJumpPage();
        }else{
            mApp.showToastLongMessage(mContext,result.getErrs());
        }
    }

    @Override
    public void editCbyfInfoResult(YfEditResultBean result) {
        if ("200".equals(result.getCode()) && result.getUs().equals("0")) {//删除本地保存数据
            mApp.showToastLongMessage(mContext,result.getReMessage());
            CbYfInfoBean localExistObj = CbYfInfoBeanDaoOpe.queryEntityForParams(mContext,mJcdInfoBean.getGEMPOINTID()+"-"+Calendar.getInstance().get(Calendar.YEAR), curtYfcodeBean.getYfCode());
            if (localExistObj != null) {
                CbYfInfoBeanDaoOpe.deleteData(mContext,localExistObj);
            }
            initJumpPage();
        }else {
            mApp.showToastLongMessage(mContext,result.getErrs());
        }
    }

    @Override
    public void removeCbyfInfoResult(YfRemoveReusltBean result) {
        if ("200".equals(result.getCode())) {
            mApp.showToastLongMessage(mContext, result.getReMessage());
            initJumpPage();
        } else {
            mApp.showToastLongMessage(mContext, result.getCode());
        }
    }

    //---------------------灌木样方---------------------------------------
    @Override
    public void findGmyfInfoResults(List<GmYfInfoBean> gmYfInfoBeanList) {
        int gmYfNums = gmYfInfoBeanList.size();
        Log.i(TAG, "findGmyfInfoResults: ------------>"+gmYfNums);
        if(gmyfQueryFlag == 1){//显示样方列表
            yfCodeBeanList.clear();
            if (gmYfNums > 0) {
                for (int i = 0; i < gmYfNums; i++) {
                    YfCodeBean bean = new YfCodeBean();
                    bean.setYfCode(gmYfInfoBeanList.get(i).getSHRUBID());
                    bean.setYfName("灌木样方" + (i + 1));
                    yfCodeBeanList.add(bean);
                }
                curtYfcodeBean = yfCodeBeanList.get(0);
                //mAgentWebX5.getJsEntraceAccess().quickCallJs("callJsWebViewInitComplete");
            }
            updateYfListUI();
        }else if(gmyfQueryFlag == 2){//新增灌木样方
            GmYfInfoBean gmObj = gson.fromJson(htmlCommitDataStr, GmYfInfoBean.class);//页面提交数据
            gmObj.setSHRUBID(String.valueOf(gmYfNums+1));
            mPersenter.addGmyfInfo(gmObj);
            Log.i(TAG, "findGmyfInfoResults: ------新增----->"+gson.toJson(gmObj));
        }else if(gmyfQueryFlag == 3){//修改灌木样方
            GmYfInfoBean serBean = gmYfInfoBeanList.get(0);
            GmYfInfoBean gmObj = gson.fromJson(htmlCommitDataStr, GmYfInfoBean.class);//页面提交数据
            gmObj.setVERSION(serBean.getVERSION());
            int gmObjWzLen = gmObj.getSHRUB_WZ().size();
            int serBeanWzlen = serBean.getSHRUB_WZ().size();
            for (int i = 0; i < gmObjWzLen; i++) {
                for (int j = 0 ; j < serBeanWzlen; j++) {
                    if (gmObj.getSHRUB_WZ().get(i).getWZDM().equals(serBean.getSHRUB_WZ().get(j).getWZDM())) {
                        gmObj.getSHRUB_WZ().get(i).setID(serBean.getSHRUB_WZ().get(j).getID());
                        gmObj.getSHRUB_WZ().get(i).setSHRUBID(serBean.getSHRUB_WZ().get(j).getSHRUBID());
                        gmObj.getSHRUB_WZ().get(i).setVERSION(serBean.getSHRUB_WZ().get(j).getVERSION());
                    }
                }
            }
            mPersenter.editGmyfInfo(gmObj);
            Log.i(TAG, "findGmyfInfoResults: ------修改----->"+gson.toJson(gmObj));
        }
        gmyfQueryFlag = 0;
    }
    @Override
    public void addGmyfInfoResult(YfEditResultBean result) {
        if ("200".equals(result.getCode()) && result.getUs().equals("0")) {//删除本地保存数据
            mApp.showToastLongMessage(mContext,result.getReMessage());
            GmYfInfoBean localExistObj = GmYfInfoBeanDaoOpe.queryEntityForParams(mContext,mJcdInfoBean.getGEMPOINTID()+"-"+Calendar.getInstance().get(Calendar.YEAR), curtYfcodeBean.getYfCode());
            if (localExistObj != null) {
                GmYfInfoBeanDaoOpe.deleteData(mContext,localExistObj);
            }
            initJumpPage();
        }else{
            mApp.showToastLongMessage(mContext,result.getErrs());
        }
    }

    @Override
    public void editGmyfInfoResult(YfEditResultBean result) {
        if ("200".equals(result.getCode()) && result.getUs().equals("0")) {//删除本地保存数据
            mApp.showToastLongMessage(mContext,result.getReMessage());
            GmYfInfoBean localExistObj = GmYfInfoBeanDaoOpe.queryEntityForParams(mContext,mJcdInfoBean.getGEMPOINTID()+"-"+Calendar.getInstance().get(Calendar.YEAR), curtYfcodeBean.getYfCode());
            if (localExistObj != null) {
                GmYfInfoBeanDaoOpe.deleteData(mContext,localExistObj);
            }
            initJumpPage();
        }else {
            mApp.showToastLongMessage(mContext,result.getErrs());
        }
    }

    @Override
    public void removeGmyfInfoResult(YfRemoveReusltBean result) {
        if ("200".equals(result.getCode())) {
            mApp.showToastLongMessage(mContext,result.getReMessage());
            initJumpPage();
        }else {
            mApp.showToastLongMessage(mContext, result.getCode());
        }
    }

    /*
        *
        * 生命周期
        * */
    @Override
    protected void onResume() {
        super.onResume();
        if (mWebviewMapview != null) {
            mWebviewMapview.onResume();
        }

    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mWebviewMapview != null) {
            mWebviewMapview.onPause();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        //取消注册传感器监听
        if (mSensorManager != null) {
            mSensorManager.unregisterListener(this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 关闭定位图层
        if (mWebviewMapview != null) {
            mWebviewMapview.onDestroy();
        }
        if (mBaiduMap != null) {
            mBaiduMap.clear();
            mBaiduMap.setMyLocationEnabled(false);
        }
        mUnBinder.unbind();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
}
